import 'package:flutter_admin/api/odoo/mrp_production_odoo_api.dart';
import 'package:flutter_admin/generated/l10n.dart';
import 'package:flutter_admin/models/odoo/mrp_production.dart';
import 'package:flutter_admin/models/odoo/price_trend.dart';
import 'package:flutter_admin/pages/common/cry/cry.dart';
import 'package:flutter_admin/pages/common/cry/cry_all.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/odoo/material/price_trend/price_trend_price_add.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/eventbus.dart';

class PriceTrendDetail extends StatefulWidget {
  MrpProduction? mrpProduction;
  PriceTrendDetail({required this.mrpProduction, Key? key}) : super(key: key);
  @override
  _PriceTrendDetailState createState() => _PriceTrendDetailState();
}

class _PriceTrendDetailState extends State<PriceTrendDetail> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page = PageModel(orders: [
    OrderItemModel(column: 'create_date', asc: false),
  ]);
  PriceTrend priceTrend = PriceTrend();
  List<PriceTrend> selectedList = [];

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _loadSelectVO();
    });
  }

  _loadSelectVO() async {
    // priceTrend.parentId = widget.mrpProduction!.id; // 查询条件
    setState(() {});
    _loadData();
  }

  @override
  Widget build(BuildContext context) {
    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(
          label: Text('产品编号'),
        ),
        DataColumn(
          label: Text('产品名称'),
        ),
        DataColumn(
          label: Text('规格型号'),
        ),
        DataColumn(
          label: Text('价格类型'),
        ),
        DataColumn(
          label: Text('价格'),
        ),
        DataColumn(
          label: Text('来源'),
        ),
        DataColumn(
          label: Text('维护时间'),
        ),
      ],
      getCells: (m) {
        PriceTrend priceTrend = PriceTrend.fromMap(m);
        return [
          DataCell(Text(priceTrend.productCode ?? '--')),
          DataCell(Text(priceTrend.productName ?? '--')),
          DataCell(Text(priceTrend.productDesc ?? '--')),
          DataCell(Text(priceTrend.priceType == '1'
              ? '合同报价'
              : priceTrend.priceType == '2'
                  ? '市场价'
                  : '--')),
          DataCell(Text(
              priceTrend.price != null ? priceTrend.price.toString() : '--')),
          DataCell(Text(priceTrend.origin ?? '--')),
          DataCell(Text(priceTrend.createDate ?? '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(children: <Widget>[
      CryButton(
        label: "新增价格",
        onPressed: () => addPrice(),
        iconData: Icons.add,
      ),
      CryButton(
        label: "获取erp价格",
        onPressed: () => getERP(),
        iconData: Icons.get_app,
      ),
      CryButtons.delete(context,
          selectedList.length != 0 ? () => _delete(selectedList) : null),
    ]);
    var result = Scaffold(
      key: scaffoldStateKey,
      appBar: AppBar(
        leading: Builder(
          builder: (BuildContext context) {
            return BackButton(onPressed: ()=>{Navigator.pop(context, true)},);
          },
        ),
        title: Text('价格明细'),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          Wrap(
            children: [
              Padding(
                padding: EdgeInsets.only(top: 24),
                child: isDisplayDesktop(context) ? buttonBar : Container(),
              )
            ],
          ),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _delete(List<PriceTrend> selectedList) async {
    cryConfirm(context, S.of(context).confirmDelete, (context) async {
      List ids = selectedList.map((v) {
        return int.parse(v.id!);
      }).toList();
      var result = await MrpProductionOdooApi.removeByIds(ids);
      if (result.success!) {
        _loadData();
        CryUtils.message(S.of(Cry.context).success);
      }
    });
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi =
        await MrpProductionOdooApi.pageDetail(data: {
      "page": page,
      "domainList": [
        ['price_id', '=', int.parse(widget.mrpProduction!.id!)]
      ]
    });
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  addPrice() async {
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: PriceTrendPriceAdd(
          priceId: widget.mrpProduction!.id,
        ),
      ),
    ).then((v) {
      if (v != null) {
        // 新增时回到第一页
        tableKey.currentState?.pageTo(0);
        _loadData();
      }
    });
  }

  getERP() async {
    ResponseBodyApi responseBodyApi =
        await MrpProductionOdooApi.getERP(widget.mrpProduction!.productCode);
    if (responseBodyApi.success!) {
      tableKey.currentState?.pageTo(0);
      _loadData();
    }
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<PriceTrend>((e) => PriceTrend.fromMap(e))
            .toList() ??
        [];
    setState(() {});
  }
}
